﻿namespace MetaDrive.VisualStudio.Services
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    
    public class LogStore
    {
        private string _templatePath;
        private EnvDTE.ProjectItem _templateProjectItem;

        public LogStore(string templatePath, EnvDTE.DTE dte)
        {
            _templatePath = templatePath;
            _templateProjectItem = dte.Solution.FindProjectItem(_templatePath);
        }

        string GetLogFilename()
        {
            return _templatePath + ".log";
        }

        public void Write(ICollection<OutputFile> outputFiles)
        {
            string templateProject = _templateProjectItem.ContainingProject.GetFilename();
            string templateDirectory = Environment.CurrentDirectory;

            if (outputFiles.Any(output =>
                !OutputInfo.SamePath(Path.GetDirectoryName(output.File), templateDirectory) ||
                (!string.IsNullOrEmpty(output.Project) && !OutputInfo.SamePath(output.Project, templateProject))))
            {
                var log = new OutputFile
                {
                    File = GetLogFilename(),
                    Project = string.Empty
                };

                outputFiles.Add(log);

                var stringBuilder = new StringBuilder(log.Content);

                stringBuilder.AppendLine("// <autogenerated>");
                stringBuilder.AppendLine("//   This file contains the list of files generated by " + Path.GetFileName(_templatePath) + ".");
                stringBuilder.AppendLine("//   It is used by T4 Toolbox (http://www.codeplex.com/t4toolbox) to automatically delete");
                stringBuilder.AppendLine("//   generated files that are no longer necessary. Do not modify this file manually. Manual");
                stringBuilder.AppendLine("//   changes may cause orphaned files and will be lost next time the code is regenerated.");
                stringBuilder.AppendLine("// </autogenerated>");

                foreach (OutputFile output in outputFiles)
                {
                    // Don't log the generated files that will be preserved
                    if (!output.PreserveExistingFile)
                    {
                        stringBuilder.AppendLine(Utils.GetRelativePath(_templatePath, output.File));
                    }
                }

                log.Content = stringBuilder.ToString();
            }
        }

        public IEnumerable<string> Read()
        {
            if (File.Exists(GetLogFilename()))
            {
                foreach (string line in File.ReadAllLines(GetLogFilename()))
                {
                    string relativePath = line.Trim();

                    // Skip blank lines
                    if (relativePath.Length == 0)
                    {
                        continue;
                    }

                    // Skip comments
                    if (relativePath.StartsWith("//", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    yield return relativePath;
                }
            }
        }
    }

}
